package com.ttn.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ttn.auth.mapper.SysRoleMapper;
import com.ttn.auth.service.SysMenuService;
import com.ttn.auth.service.SysRoleService;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.auth.SysMenu;
import com.ttn.common.core.entity.auth.SysRole;
import com.ttn.common.core.entity.auth.query.SysRolePageQuery;
import com.ttn.common.core.entity.auth.vo.SysRolePageVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Objects;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysMenuService sysMenuService;


    @Override
    public Result querySysRolePage(SysRolePageQuery sysRolePageQuery) {
        LambdaQueryWrapper<SysRole> sysRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysRoleLambdaQueryWrapper.like(StrUtil.isNotBlank(sysRolePageQuery.getName()), SysRole::getName, sysRolePageQuery.getName());
        sysRoleLambdaQueryWrapper.eq(Objects.nonNull(sysRolePageQuery.getStatus()), SysRole::getStatus, sysRolePageQuery.getStatus());
        sysRoleLambdaQueryWrapper.eq(Objects.nonNull(sysRolePageQuery.getDeleted()), SysRole::getDeleted,
                sysRolePageQuery.getDeleted());
        IPage<SysRole> page = new Page<>(sysRolePageQuery.getPageNum(), sysRolePageQuery.getPageSize());
        IPage<SysRole> sysRolePage = this.page(page, sysRoleLambdaQueryWrapper);
        return Result.success(sysRolePage);
    }

    @Override
    public Result querySysRoleById(Integer id) {
        SysRolePageVO sysRolePageVO = new SysRolePageVO();
        sysRolePageVO.setSysRole(this.getById(id));
        if (Objects.nonNull(sysRolePageVO.getSysRole()) && StrUtil.isNotBlank(sysRolePageVO.getSysRole().getMenus())) {
            LambdaQueryWrapper<SysMenu> sysMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysMenuLambdaQueryWrapper.in(SysMenu::getId, Arrays.asList(sysRolePageVO.getSysRole().getMenus().split(",")));
            sysRolePageVO.setSysMenuList(sysMenuService.list(sysMenuLambdaQueryWrapper));
        }

        return Result.success(sysRolePageVO);
    }
}
